﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Caching;
using System.Xml.Linq;
using Netkk.Common;
using Netkk.Common.Interfaces.Repositories;
using Netkk.Common.Models;

namespace Netkk.Data.Repositories
{
    public class UserRepository : BaseRepository, IUserRepository
    {
        private readonly string userPath;
        private IRoleRepository roleRepository;

        protected XDocument UserDocument
        {
            get { return CacheWrapper.Load("users", new CacheDependency(userPath), () => XDocument.Load(userPath)); }
        }

        public UserRepository(IRoleRepository roleRepository)
        {
            this.roleRepository = roleRepository;
            userPath = string.Concat(ConnectionString, "Users.xml");
        }

        public IEnumerable<User> Select()
        {
            IEnumerable<User> users =
                from u in UserDocument.Element("Users").Elements("User")
                select getUserFromXElement(u);

            return users;
        }

        /// <summary>
        /// Gets the user from X element.
        /// </summary>
        /// <param name="XUser">The X user.</param>
        /// <returns></returns>
        private User getUserFromXElement(XElement XUser)
        {
            return new User
            {
                Id = XUser.Element("Id").Value.ToOrDefault<Guid>(),
                FirstName = XUser.Element("Name").Value,
                LastName = XUser.Element("SureName").Value,
                Email = XUser.Element("Email").Value,
                Image = XUser.Element("Image").Value,
                Website = XUser.Element("Website").Value,
                Description = XUser.Element("Description").Value,
                Role = getRoleById(XUser.Element("RoleId").Value.ToOrDefault<Guid>()),
                Name = XUser.Element("Login").Value,
                Password = XUser.Element("Password").Value,
                IsValid = XUser.Element("IsValid").Value.ToOrDefault<bool>(),
                AllowShowProfile = XUser.Element("AllowShowProfile").Value.ToOrDefault<bool>(),
                AllowSendNewsletter = XUser.Element("AllowSendNewsletter").Value.ToOrDefault<bool>(),
                AllowSendEmails = XUser.Element("AllowSendEmails").Value.ToOrDefault<bool>()
            };
        }

        private UserRole getRoleById(Guid roleId)
        {
            IEnumerable<UserRole> roles = roleRepository.Select();
            return roles.Where(r => r.Id == roleId).FirstOrDefault();
        }

        public void Delete(User user)
        {
            XElement xuser = (from u in UserDocument.Element("Users").Elements("User")
                              where u.Element("Id").Value.ToOrDefault<Guid>() == user.Id
                              select u).FirstOrDefault();
            if (xuser != null)
            {
                xuser.Remove();
                UserDocument.Save(userPath);
            }
        }

        public void Save(User user)
        {
            XElement xuser = (from u in UserDocument.Element("Users").Elements("User")
                              where u.Element("Id").Value.ToOrDefault<Guid>() == user.Id
                              select u).FirstOrDefault();
            if (xuser == null)
            {
                xuser = new XElement("User");
                UserDocument.Element("Users").Add(xuser);
            }
            else
            {
                xuser.RemoveAll();
            }

            xuser.Add(
                new XElement("Id") { Value = user.Id.ToString("B") },
                new XElement("Name") { Value = user.FirstName ?? String.Empty },
                new XElement("SureName") { Value = user.LastName ?? String.Empty },
                new XElement("Email") { Value = user.Email },
                new XElement("Website") { Value = user.Website ?? String.Empty },
                new XElement("Image") { Value = user.Image ?? String.Empty },
                new XElement("Description") { Value = user.Description ?? String.Empty },
                new XElement("RoleId") { Value = user.Role.Id.ToString("B") },
                new XElement("Login") { Value = user.Name },
                new XElement("Password") { Value = user.Password },
                new XElement("IsValid") { Value = user.IsValid.ToString() },
                new XElement("AllowShowProfile") { Value = user.AllowShowProfile.ToString() },
                new XElement("AllowSendNewsletter") { Value = user.AllowSendNewsletter.ToString() },
                new XElement("AllowSendEmails") { Value = user.AllowSendEmails.ToString() });

            UserDocument.Save(userPath);
        }




    }

}
